# 自动扫描插件
import pkgutil
from .base_plugin import BasePlugin
import importlib.util
import sys


def load_plugins():
    plugins = {}
    for importer, modname, ispkg in pkgutil.iter_modules(__path__):
        if modname and not ispkg and modname != 'base_plugin':
            # 构建完整模块名
            full_modname = f"{__package__}.{modname}"

            try:
                # 动态导入模块
                spec = importlib.util.find_spec(full_modname)
                module = importlib.util.module_from_spec(spec)
                sys.modules[full_modname] = module
                spec.loader.exec_module(module)

                # 遍历模块中的类
                for name, obj in module.__dict__.items():
                    if isinstance(obj, type) and \
                            issubclass(obj, BasePlugin) and \
                            hasattr(obj, 'name') and \
                            (obj.name is not None and obj.name != ""):
                        plugins[obj.name] = obj()
            except Exception as e:
                print(f"Failed to load {modname}: {e}")

    return plugins


registered_plugins = load_plugins()


def get_plugin_by_name(name):
    plugin = registered_plugins.get(name)
    if not plugin:
        raise ValueError(f"Plugin {name} not found")
    return plugin
